package com.xingshang.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xingshang.pojo.User;
import com.xingshang.service.UserService;
import com.xingshang.mapper.UserMapper;
import com.xingshang.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 87547
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-12-05 22:15:33
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Autowired
    private FileUploadUtil fileUploadUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtHelper jwtHelper;

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    @Override
    public Result login(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());

        User one = userMapper.selectOne(queryWrapper);
        if (one == null) {
            return Result.build(null, ResultCodeEnum.USERNAME_ERROR);
        }
        System.out.println("user.getPassword() = " + user.getPassword());
        if (!StringUtils.isEmpty(user.getPassword()) && MD5Util.encrypt(user.getPassword()).equals(one.getPassword())) {
            String token = jwtHelper.createToken(Long.valueOf(one.getUserid()));
            Map data = new HashMap();
            data.put("token", token);
            return Result.ok(data);
        }
        return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
    }

    @Override
    public Result getUserInfo(String token) {
        boolean expiration = jwtHelper.isExpiration(token);
        if (expiration) {
            return Result.build(null, ResultCodeEnum.NOTLOGIN);
        }
        Long userId = jwtHelper.getUserId(token);
        if (userId != null) {
            User user = userMapper.selectById(userId);//要用这个方法就要给实体类的主键加上tableid
            user.setPassword(null);
            Map data = new HashMap();
            data.put("user", user);
            return Result.ok(data);
        }
        return Result.build(null, ResultCodeEnum.NOTLOGIN);
    }

    @Override
    public Result checkUserName(String username) {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        Long count = userMapper.selectCount(queryWrapper);
        if (count == 0) {
            return Result.ok(null);
        }
        return Result.build(null, ResultCodeEnum.USERNAME_USED);
    }

    @Override
    public Result regist(User user) {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        Long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            return Result.build(null, ResultCodeEnum.USERNAME_USED);
        }
        user.setPassword(MD5Util.encrypt(user.getPassword()));
        userMapper.insert(user);

        return Result.ok(null);
    }

    @Override
    public Result wxlogin(String code) {

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        HttpResponse response = HttpRequest.get(url).execute();
        if (response.getStatus() == 200) {
            String resp = response.body();
            JSONObject jsonResponse = JSONUtil.parseObj(resp);

            String openid = jsonResponse.getStr("openid");
            String session_key = jsonResponse.getStr("session_key");
            System.out.println("openid = " + openid);
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getOpenid, openid);
            User one = userMapper.selectOne(queryWrapper);
            if (one == null) {
                one = new User();
                one.setOpenid(openid);
                one.setUsername("wx_" + openid.substring(0, 5));
                one.setNickname("wx_" + openid.substring(0, 5));

                one.setPassword(MD5Util.encrypt("123456"));
                userMapper.insert(one);
            }
            String token = jwtHelper.createToken(Long.valueOf(one.getUserid()));
            Map data = new HashMap();
            data.put("token", token);
            return Result.ok(data);
        }


        return Result.build(null, ResultCodeEnum.HTTP_REQUEST_ERROR);
    }

    @Override
    public Result uploadPhoto(MultipartFile file, String token) {
        Long userId = jwtHelper.getUserId(token);
        String photoUrl = fileUploadUtil.uploadFile(file, "user" + userId);
//        System.out.println("photoUrl = " + photoUrl);

        User user = userMapper.selectById(userId);
        user.setProfilePicture(photoUrl);
        int i = userMapper.updateById(user);
        if (i == 0) {
            return Result.build(null, ResultCodeEnum.UPDATE_ERROR);
        }
        return Result.ok(photoUrl);
    }


}




